package cn.edu.mju.dal.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import cn.edu.mju.dal.IMarkInfoDAO;
import cn.edu.mju.db.DbHelper;
import cn.edu.mju.model.MarkInfo;
import cn.edu.mju.model.Student;
import cn.edu.mju.utils.Pager;

public class MarkInfoDAO implements IMarkInfoDAO {

	@Override
	public void save(MarkInfo m) {
		Session session = DbHelper.getSession();
		Transaction ts = session.beginTransaction();
		if(m.getmId() != null && m.getmId() > 0)
		{
			session.update(m);
		}
		else
		{
			session.save(m);
		}
		ts.commit();
		session.close();
		
	}

	@Override
	public Pager findPager(Integer page, MarkInfo m) {
		// TODO Auto-generated method stub
		Session session = DbHelper.getSession();		
		//2、hql查询
		String hqlTotal = "select count(*) from MarkInfo where 1=1";
		String hqlSelect = "from MarkInfo order by id desc";
		
		
		StringBuffer hqlWhere = new StringBuffer("");    //UserGroup类名
		if(m.getMark() != null && !"".equals(m.getMark()))
		{
			hqlWhere.append("and mark like :mark ");
		}		
		//找出数据总数
		Query query = session.createQuery(hqlTotal + hqlWhere.toString());
		
		//模糊查询
		if(m.getMark() != null && !"".equals(m.getMark()))
		{
			query.setString("mark","%" + m.getMark() + "%");
		}
		
		int rows = ((Long) query.getSingleResult()).intValue();		//条数
		Pager pager = new Pager();			//实例化翻页的方法 （调用Pager方法）
		pager.setRows(rows);
		pager.setPage(page);
		
		query = session.createQuery(hqlSelect + hqlWhere.toString());	//查询UserGroup数据,显示在列表
		if(m.getMark() != null && !"".equals(m.getMark()))
		{
			query.setString("mark","%" + m.getMark() + "%");
		}
		query.setFirstResult((pager.getPage()-1)* pager.getPageSize());
		query.setMaxResults(pager.getPageSize());
		pager.setData(query.list());
		//pager.getPages();
		session.close();
		return pager;
	}

	@Override
	public void delete(Integer mId) {
		Session session = DbHelper.getSession();
		Transaction ts = session.beginTransaction();
		MarkInfo markInfo = session.get(MarkInfo.class, mId);
		session.delete(markInfo);
		ts.commit();
		session.close();
		
	}

	@Override
	public MarkInfo findById(Integer mId) {
		Session session = DbHelper.getSession();
		String hql = "from MarkInfo where mId=:mId";
		Query query = session.createQuery(hql);
		query.setInteger("mId", mId);
		MarkInfo markInfo = (MarkInfo) query.getSingleResult();
		session.close();
		return markInfo;
	}

	@Override
	public List<MarkInfo> findAll(MarkInfo m) {
		Session session = DbHelper.getSession();
		String hql = new String("from MarkInfo");
		Query query = session.createQuery(hql);
		List<MarkInfo> list = query.list();
		session.close();
		return list;
	}

}
